package xyz.hubery.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import xyz.hubery.mapper.BrandMapper;
import xyz.hubery.mapper.GoodsImageMapper;
import xyz.hubery.mapper.GoodsMapper;
import xyz.hubery.model.Constants;
import xyz.hubery.pojo.*;
import xyz.hubery.service.GoodsService;
import xyz.hubery.service.SearchService;

import java.util.ArrayList;
import java.util.List;

@DubboService
@Transactional
@Slf4j
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private GoodsImageMapper goodsImageMapper;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Transactional
    @Override
    public void add(Goods goods) {
        // 1、添加商品
        goodsMapper.insert(goods);
        Long gid = goods.getId();
        // 2、保存商品图片
        List<GoodsImage> images = goods.getImages();
        if(images != null) {
            for (GoodsImage image : images) {
                image.setGoodsId(gid);
                goodsImageMapper.insert(image);
            }
        }
        // 3、添加商品-规格项数据
        List<Specification> specifications = goods.getSpecifications();
        List<Long> specOptionIds = new ArrayList<>(); // 保存规格项id
        if(specifications != null) {
            for (Specification specification : specifications) {
                List<SpecificationOption> specificationOptions = specification.getSpecificationOptions();
                if(specificationOptions != null) {
                    for (SpecificationOption option : specificationOptions) {
                        specOptionIds.add(option.getId());
                    }
                }
            }
        }
        if(!specOptionIds.isEmpty()) {
            goodsMapper.addSpecOption(gid, specOptionIds);
        }

        // 将商品数据同步到es中
        GoodsDesc goodsDesc = findDesc(gid);
        goodsDesc.setTag(Constants.SYNC_GOODS_TAG);
        rocketMQTemplate.syncSendOrderly(Constants.SYNC_GOODS_TOPIC,goodsDesc, gid.toString());
    }

    @Transactional
    @Override
    public void update(Goods goods) {

        // 更新商品
        goodsMapper.updateById(goods);
        Long goodId = goods.getId();
        // 删除商品图片
        goodsImageMapper.delete(new LambdaQueryWrapper<GoodsImage>().eq(GoodsImage::getGoodsId,goodId));
        // 添加商品图片
        List<GoodsImage> images = goods.getImages();
        if(images != null) {
            for (GoodsImage image : images) {
                image.setGoodsId(goodId);
                goodsImageMapper.insert(image);
            }
        }
        // 删除商品-规格项数据
        goodsMapper.deleteGoodsSpecOption(goodId);
        // 添加商品-规格项数据
        List<Specification> specifications = goods.getSpecifications();
        List<Long> specOptionIds = new ArrayList<>(); // 保存规格项id
        if(specifications != null) {
            for (Specification specification : specifications) {
                List<SpecificationOption> specificationOptions = specification.getSpecificationOptions();
                if(specificationOptions != null) {
                    for (SpecificationOption option : specificationOptions) {
                        specOptionIds.add(option.getId());
                    }
                }
            }
        }
        if(!specOptionIds.isEmpty()) {
            goodsMapper.addSpecOption(goodId, specOptionIds);
        }


        // 将商品数据同步到es中
        GoodsDesc goodsDesc = findDesc(goodId);
        goodsDesc.setTag(Constants.SYNC_GOODS_TAG);
        rocketMQTemplate.syncSendOrderly(Constants.SYNC_GOODS_TOPIC,goodsDesc, goodId.toString());


        // 更新用户购物车缓存数据
        CartGoods cartGoods = goods2CartGoods(goods);
        cartGoods.setTag(Constants.SYNC_GOODS_TAG);
        // 发送顺序消息
        rocketMQTemplate.asyncSendOrderly(Constants.UPDATE_CART_TOPIC,cartGoods, goodId.toString(), new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("更新用户购物车缓存数据成功");
            }

            @Override
            public void onException(Throwable throwable) {
                log.error("更新用户购物车缓存数据失败：{}", throwable.getMessage());
            }
        });
    }

    private CartGoods goods2CartGoods(Goods goods) {
        CartGoods cartGoods = new CartGoods();
        cartGoods.setGoodId(goods.getId());
        cartGoods.setGoodsName(goods.getGoodsName());
        cartGoods.setPrice(goods.getPrice());
        cartGoods.setHeaderPic(goods.getHeaderPic());
        return cartGoods;
    }

    /**
     * 根据id查询商品详情
     * @param id
     * @return
     */
    @Override
    public Goods findById(Long id) {
        return goodsMapper.findById(id);
    }

    /**
     * 上架/下架商品
     * @param id
     * @param isMarketable
     */
    @Override
    public void putAway(Long id, Boolean isMarketable) {
        // 查询商品
        Goods goods = goodsMapper.selectById(id);
        if(goods != null){
            goods.setIsMarketable(isMarketable);
            goodsMapper.updateById(goods);
            // 上架时数据同步到ES，下架时删除ES数据
            GoodsDesc goodsDesc = findDesc(id);
            if (isMarketable) {
                goodsDesc.setTag(Constants.SYNC_GOODS_TAG); // 同步商品
            }else {
                goodsDesc.setTag(Constants.DEL_GOODS_TAG); // 删除商品

                CartGoods cartGoods = new CartGoods();
                cartGoods.setGoodId(id);
                cartGoods.setTag(Constants.DEL_GOODS_TAG);
                // 发送顺序消息
                rocketMQTemplate.asyncSendOrderly(Constants.UPDATE_CART_TOPIC,cartGoods, id.toString(), new SendCallback() {
                    @Override
                    public void onSuccess(SendResult sendResult) {
                        log.info("更新用户购物车缓存数据成功");
                    }

                    @Override
                    public void onException(Throwable throwable) {
                        log.error("更新用户购物车缓存数据失败：{}", throwable.getMessage());
                    }
                });
            }
            rocketMQTemplate.syncSendOrderly(Constants.SYNC_GOODS_TOPIC,goodsDesc, id.toString());
        }
    }

    @Override
    public Page<Goods> search(Goods goods, int page, int size) {
        // 构架查询条件
        Page<Goods> pageInfo = Page.of(page, size);
        return goodsMapper.selectPage(pageInfo,new LambdaQueryWrapper<Goods>()
                .like(goods != null && StringUtils.hasText(goods.getGoodsName()),Goods::getGoodsName,goods.getGoodsName()));
    }


    @Override
    public List<GoodsDesc> findAll() {
        return goodsMapper.findAll();
    }


    @Override
    public GoodsDesc findDesc(Long id) {
        return goodsMapper.findDesc(id);
    }
}
